package com.sany.taskmanager.ui.activity;

import static com.sany.taskmanager.global.Key.IntentKey.ACTIVITY_INDEX;
import static com.sany.taskmanager.global.Key.IntentKey.MATERIAL_NUM;

import android.app.Activity;
import android.content.Intent;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.sany.taskmanager.R;
import com.sany.taskmanager.bean.ColorBean;
import com.sany.taskmanager.bean.TaskGroupBean;
import com.sany.taskmanager.bean.TaskInfoBean;
import com.sany.taskmanager.databinding.ActivitySendedTaskBinding;
import com.sany.taskmanager.global.Constants;
import com.sany.taskmanager.http.IHttpCallBack;
import com.sany.taskmanager.manager.DataManager;
import com.sany.taskmanager.ui.adapter.TaskSendedAdapter;
import com.sany.taskmanager.ui.widget.ModifyTaskInfoDialog;
import com.sany.taskmanager.util.LogUtil;
import com.sany.taskmanager.util.ToastUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 已下发任务面
 */
public class SendedTaskActivity extends BaseActivity<ActivitySendedTaskBinding> {
    private TaskSendedAdapter mAdapter;
    private List<TaskInfoBean> mTaskList;
    private final List<TaskGroupBean> mTaskGroupList = new ArrayList<>();
    private ModifyTaskInfoDialog modifyTaskInfoDialog;
    private int currentPosition;
    private ActivityResultLauncher<Intent> scanResult;

    @Override
    protected void initData() {
        scanResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            //此处是跳转的result回调方法
            if (result.getData() != null && result.getResultCode() == Activity.RESULT_OK) {
                String materialNum = result.getData().getStringExtra(MATERIAL_NUM);
                // 修改下发任务信息的弹框，更新物料编码
                if (modifyTaskInfoDialog != null && modifyTaskInfoDialog.isShowing()) {
                    modifyTaskInfoDialog.setMaterialNum(materialNum);
                }
            }
        });
        vBinding.tvBack.setOnClickListener(v -> finish());
        mAdapter = new TaskSendedAdapter(this);
        mAdapter.setOnOperateListener(new TaskSendedAdapter.OnOperateListener() {
            @Override
            public void modify(int position) {
                showModifyInventoryDialog(position);
            }

            @Override
            public void cancel(TaskInfoBean item) {
                showTipDialog(getString(R.string.tip_cancel_have_send_task), () -> {
                    cancelTask(item);
                });
            }
        });
        vBinding.rvTaskInfo.setAdapter(mAdapter);
        getSendTaskList();
    }

    /**
     * 获取已下发任务
     */
    private void getSendTaskList() {
        showLoading();
        compositeDisposable.add(taskViewModel.getSendTaskList(new IHttpCallBack<List<TaskInfoBean>>() {
            @Override
            public void onSuccess(List<TaskInfoBean> taskList) {
                hideLoading();
                mTaskList = taskList;
                // 刷新UI
                refreshUI();
                // 默认展开所有的成套任务
                for (TaskGroupBean groupBean : mTaskGroupList) {
                    if (groupBean.isExpandable()) {
                        mAdapter.expandGroup(groupBean);
                    }
                }
            }

            @Override
            public void onFailed(String message) {
                hideLoading();
                LogUtil.e(message, SendedTaskActivity.class);
            }
        }));
    }

    /**
     * 刷新UI
     */
    private void refreshUI() {
        mTaskGroupList.clear();
        if (mTaskList == null || mTaskList.isEmpty()) {
            mAdapter.setTaskList(mTaskGroupList);
            vBinding.viewEmpty.setVisibility(View.VISIBLE);
            vBinding.rvTaskInfo.setVisibility(View.GONE);
            return;
        }
        vBinding.viewEmpty.setVisibility(View.GONE);
        vBinding.rvTaskInfo.setVisibility(View.VISIBLE);
        Map<String, List<TaskInfoBean>> taskMap = new LinkedHashMap<>();
        int i = 1;
        for (TaskInfoBean taskInfoBean : mTaskList) {
            taskMap.computeIfAbsent(taskInfoBean.getTaskNumber(), k -> new ArrayList<>());
            taskMap.get(taskInfoBean.getTaskNumber()).add(taskInfoBean);
        }
        for (Map.Entry<String, List<TaskInfoBean>> entry : taskMap.entrySet()) {
            TaskGroupBean groupBean = new TaskGroupBean();
            List<TaskInfoBean> childList = entry.getValue();
            groupBean.setHeaderBean(childList.get(0));
            groupBean.setList(childList.subList(1, childList.size()));
            mTaskGroupList.add(groupBean);
        }
        mAdapter.setTaskList(mTaskGroupList);
    }

    /**
     * 取消任务
     */
    private void cancelTask(TaskInfoBean item) {
        showLoading();
        compositeDisposable.add(taskViewModel.cancelTask(item.getTaskId(), new IHttpCallBack<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {
                hideLoading();
                mTaskList.remove(item);
                // 刷新UI
                refreshUI();
                ToastUtil.showToast(SendedTaskActivity.this, getString(R.string.tip_cancel_success));
            }

            @Override
            public void onFailed(String message) {
                hideLoading();
                ToastUtil.showToast(SendedTaskActivity.this, String.format(getString(R.string.format_cancel_failed), message));

            }
        }));
    }

    /**
     * 修改大臂库位信息：主要修改大臂颜色和库位编号
     */
    private void showModifyInventoryDialog(int position) {
        currentPosition = position;
        if (modifyTaskInfoDialog == null) {
            modifyTaskInfoDialog = new ModifyTaskInfoDialog(this, mTaskList.get(currentPosition));
            modifyTaskInfoDialog.setOnModifyTaskInfoListener(new ModifyTaskInfoDialog.OnModifyTaskInfoListener() {
                @Override
                public void modifyTaskInfo(int colorType, String colorCode, String colorValue, int headColorType, String headColorCode, String headColorValue, String materialNum, int boomType, int count) {
                    modifyTask(mTaskList.get(currentPosition).getTaskId(), materialNum, colorType, boomType);
                }

                @Override
                public void goScan() {
                    // 跳转到扫码页面
                    scanResult.launch(new Intent(SendedTaskActivity.this, ScanActivity.class).putExtra(ACTIVITY_INDEX, Constants.ScanIndex.ACTIVITY_TASK));
                }
            });
        } else {
            modifyTaskInfoDialog.setTaskInfo(mTaskList.get(currentPosition));
        }
        if (!modifyTaskInfoDialog.isShowing()) {
            modifyTaskInfoDialog.show();
        }

    }

    /**
     * 修改任务
     */
    private void modifyTask(String taskId, String materialNum, int colorType, int boomType) {
        showLoading();
        compositeDisposable.add(taskViewModel.modifyTask(taskId, materialNum, colorType, boomType, new IHttpCallBack<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {
                hideLoading();
                // 刷新UI
                mTaskList.get(currentPosition).setColorType(colorType);
                ColorBean colorBean = DataManager.getInstance().getColorMap().get(colorType);
                if (colorBean != null) {
                    mTaskList.get(currentPosition).setColorName(colorBean.getColorName());
                }
                mTaskList.get(currentPosition).setMaterialNum(materialNum);
                mTaskList.get(currentPosition).setBoomType(boomType);
                // 刷新UI
                refreshUI();
                ToastUtil.showToast(SendedTaskActivity.this, getString(R.string.tip_modify_success));
            }

            @Override
            public void onFailed(String message) {
                hideLoading();
                ToastUtil.showToast(SendedTaskActivity.this, String.format(getString(R.string.format_modify_failed), message));
            }
        }));
    }

}
